package org.example.web;

import com.google.common.collect.Lists;
import freemarker.template.TemplateException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.component.FreeMakerHelper;
import org.example.utils.PdfUtils;
import org.example.web.request.PdfModelData;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author wangfei
 */
@Slf4j
@RestController
@RequestMapping("/pdf")
@RequiredArgsConstructor
public class PdfGenerateController {

    private final FreeMakerHelper freeMakerHelper;

    @PostMapping("export")
    public void generatePdf(@RequestBody PdfModelData pdfModelData) {
        File file = new File("test.pdf");
        try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
            String html = freeMakerHelper.process("test.html", pdfModelData);
            byte[] bytes = PdfUtils.merge(Lists.newArrayList(PdfUtils.html2Pdf(html)));
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
            log.info("生成pdf成功,path:{}", file.getAbsolutePath());
        } catch (Exception e) {
            log.error("生成pdf失败，message：{}", e.getMessage(), e);
        }
    }
}
